package servlet;

import model.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import java.io.IOException;
import java.io.File;
import java.util.Date;

@WebServlet(name = "user_register", urlPatterns = "/user_register")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024, // 1 MB
    maxFileSize = 1024 * 1024 * 10,  // 10 MB
    maxRequestSize = 1024 * 1024 * 15 // 15 MB
)
public class RegisterUserServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置请求编码
            request.setCharacterEncoding("UTF-8");
            
            // 获取表单数据
            String nickname = request.getParameter("nickname");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            
            // 处理头像上传
            String avatarPath = "/picture/avatar.png"; // 默认头像
            Part avatarPart = request.getPart("avatar");
            if (avatarPart != null && avatarPart.getSize() > 0) {
                String fileName = new Date().getTime() + getFileExtension(avatarPart);
                String uploadPath = getServletContext().getRealPath("/picture");
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    if (!uploadDir.mkdirs()) {
                        throw new IOException("Failed to create directory: " + uploadPath);
                    }
                }
                
                avatarPart.write(uploadPath + File.separator + fileName);
                avatarPath = "/picture/" + fileName;
            }
            
            // 创建用户对象并设置属性
            User user = new User();
            user.setNickname(nickname);
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setAvatar(avatarPath);
            user.setCreate_time(new Date());
            user.setAdmin(false);

            // 注册用户
            boolean isSuccess = userService.register(user);
            String message = userService.getRegisterResultMessage(isSuccess, username, email);
            request.setAttribute("msg", message);

            if (isSuccess) {
                // 注册成功后重定向到登录页面
                response.sendRedirect(request.getContextPath() + "/user_login.jsp");
            } else {
                request.getRequestDispatcher("/user_register.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "注册失败：" + e.getMessage());
            request.getRequestDispatcher("/user_register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求，跳转到注册页面
        request.getRequestDispatcher("/user_register.jsp").forward(request, response);
    }

    private String getFileExtension(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String fileName = token.substring(token.indexOf("=") + 2, token.length() - 1);
                int dotIndex = fileName.lastIndexOf(".");
                return dotIndex > 0 ? fileName.substring(dotIndex) : "";
            }
        }
        return "";
    }
}